package cn.safekeeper.guide.admin.controller.system;

import cn.safekeeper.common.annotations.SafeKeeperHasPermission;
import cn.safekeeper.core.SafeKeeper;
import cn.safekeeper.guide.admin.constant.Constants;
import cn.safekeeper.guide.admin.constant.MsgObj;
import cn.safekeeper.guide.admin.constant.UserConstants;
import cn.safekeeper.guide.admin.controller.BaseController;
import cn.safekeeper.guide.admin.domain.entity.SysRole;
import cn.safekeeper.guide.admin.domain.entity.SysUser;
import cn.safekeeper.guide.admin.domain.page.TableDataInfo;
import cn.safekeeper.guide.admin.service.ISysPostService;
import cn.safekeeper.guide.admin.service.ISysRoleService;
import cn.safekeeper.guide.admin.service.ISysUserService;
import cn.safekeeper.guide.admin.utils.StringUtils;
import cn.safekeeper.guide.admin.utils.sign.Md5Utils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 用户信息
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    /**
     * 获取用户列表
     */
    @GetMapping("/list")
    @SafeKeeperHasPermission(permissions = {"system:user:list"})
    public TableDataInfo list(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }


    /**
     * 根据用户编号获取详细信息
     */
    @GetMapping("/query")
    public MsgObj getInfo(HttpServletRequest request) {
        String userIdStr = request.getParameter("userId");
        Long userId = null;
        if(StringUtils.isNotBlank(userIdStr)){
            userId = Long.parseLong(userIdStr);
        }
        MsgObj ajax = MsgObj.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            ajax.put(MsgObj.DATA_TAG, userService.selectUserById(userId));
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PostMapping("/add")
    public MsgObj add(@Validated @RequestBody SysUser user) {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
            return MsgObj.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return MsgObj.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return MsgObj.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(getUsername());
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PutMapping("/edit")
    public MsgObj edit(@Validated @RequestBody SysUser user) {
        int ret = userService.checkUserAllowed(user);
        if(ret < 0){
            return error("不允许操作超级管理员用户");
        }
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return MsgObj.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return MsgObj.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/remove")
    public MsgObj remove(@RequestParam Long[] userIds) {
        if (ArrayUtils.contains(userIds, getUserId())) {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PutMapping("/resetPwd")
    public MsgObj resetPwd(@RequestBody SysUser user) {
        int ret = userService.checkUserAllowed(user);
        if(ret < 0){
            return error("不允许操作超级管理员用户");
        }
        user.setPassword(Md5Utils.hash(Constants.INIT_PASSWORD));
        user.setUpdateBy(getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PutMapping("/changeStatus")
    public MsgObj changeStatus(@RequestBody SysUser user) {
        int ret = userService.checkUserAllowed(user);
        if(ret < 0){
            return error("不允许操作超级管理员用户");
        }
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @GetMapping("/authRole/query")
    public MsgObj getAuthRole(Long userId) {
        if(userId == null){
            return error("缺少参数用户ID");
        }
        MsgObj ajax = MsgObj.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @PutMapping("/authRole/edit")
    public MsgObj updateAuthRole(Long userId, Long[] roleIds) {
        userService.insertUserAuth(userId, roleIds);
        //更新角色
        SafeKeeper.safeDefault().clearRoleOrPermissionCacheData(getUserId(), Constants.ROLE_CACHE_MARK);
        return success();
    }
}
